package com.pig4cloud.pig.admin.api.util;

import com.pig4cloud.pig.admin.api.dto.loginDTO;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;


public class FeignClientRequestInterceptor implements RequestInterceptor {
	@Override
	public void apply(RequestTemplate template) {
		HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		if (httpServletRequest != null) {
			//获取头信息
			Map<String, String> headers = getHeaders(httpServletRequest);
			// 传递所有请求头,防止部分丢失
			Set<Map.Entry<String, String>> headerSet = headers.entrySet();

			//RequestTemplate添加请求头
			for (Map.Entry<String, String> e :headerSet) {
				template.header(e.getKey(), e.getValue());
			}
			// 请求客户端信息、权限信息
			if (httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION) == null) {
				//添加客户端信息
//				byte[] auth64Encode = Base64.getEncoder().encode(ConstantString.CLIENT_ID_SECRET.getBytes(StandardCharsets.UTF_8));
//				template.header(HttpHeaders.AUTHORIZATION, new String(auth64Encode));
			}
			//log.debug("FeignRequestInterceptor:{}", template.toString());
		}
	}

	/**
	 * 获取头信息
	 *
	 * @param request
	 * @return
	 */
	private Map<String, String> getHeaders(HttpServletRequest request) {
		Map<String, String> headerMap = new LinkedHashMap<>();
		Enumeration<String> enumeration = request.getHeaderNames();
		if (Objects.nonNull(enumeration)) {
			while (enumeration.hasMoreElements()) {
				String key = enumeration.nextElement();
				String value = request.getHeader(key);
				headerMap.put(key, value);
			}
		}
		return headerMap;
	}

	public static HttpEntity httpHeader(loginDTO param){
		HttpEntity http = null;
		try {
			String clientId="pig";
			String clientSecret="pig";
			String Authorization ="Basic "+ new String(Base64.getEncoder().encode((clientId+":"+clientSecret).getBytes()),"UTF-8");
			MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
			//String str="Basic cGlnOnBpZw==";
			headers.add("Authorization",Authorization);	//cGlnOnBpZw==
			//body
			MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
			body.add("username",param.getUsername());
			body.add("password",new String(param.getPassword().getBytes(),"UTF-8"));
			body.add("grant_type","password");
			body.add("scope","server");

			http = new HttpEntity(body,headers);
		}catch (Exception e) {
			e.printStackTrace();
		}

		return http;
	}


}
